<?php
namespace Home\Controller;
use Common\Controller\CommonController;
class HomeController extends CommonController {
	protected $AppSecret = '536887f16f2fe2a8d8d9c88c5441af6e';
	protected $AppID = 'wx57b559484ac7a0c1';
    protected $assess_token = '';
 		public function _initialize(){

 		    parent::_initialize();
 		}
 		//////////////////////////////////////以下  微信授权
 		// 使用curl的GET请求数据  返回数组
 		protected function curl_get($http){
 		    //初始化
 		    $ch = curl_init();
 		    //设置选项，包括URL
 		    curl_setopt($ch, CURLOPT_URL, $http);
 		    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 		    curl_setopt($ch, CURLOPT_HEADER, 0);
 		    //执行并获取HTML文档内容
 		    $output = curl_exec($ch);
 		    //释放curl句柄
 		    curl_close($ch);
 		    //打印获得的数据
 		    $result = json_decode($output,true);
 		    return $result;
 		}
 		
 		public function userAuthorize($a) {


 		  //  $redirect_uri = urlencode('http://sc-wscjf.91quyum.com');
            $redirect_uri = urlencode('http://ydp.mylei.cn');
 		    //dump($redirect_uri);die;
 		    // $get_token_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->AppID."& redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base#wechat_redirect";
 		    $get_token_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->AppID."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=".cookie('my_cnt')."#wechat_redirect";
 		    // dump($get_token_url);die;
 		    header("Location:".$get_token_url);
 		
 		
 		}
 		
 		// /**
 		 // * 微信登录
 		 // */
 		public function weiXinLogin($aaa = "") {
 		    $appid = $this->AppID;
 		    $secret = $this->AppSecret;
 		    if (!isset($_GET["code"])) {
 		        $this->userAuthorize($aaa);
 		    }
 		    $code = $_GET["code"];
            cookie('my_cnt',$_GET["state"]);
                  //   var_dump($appid);exit();
 		    // dump($code);
 		    // 获取access_token、openid等其他信息
 		    $get_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
 		    $res = file_get_contents($get_token_url);
 		    // 解析返回结果
 		    //dump($res);die;
 		    $json_obj = json_decode($res, true);
 		    return $json_obj;
 		    // dump($json_obj);
 		
 		    // dump($_SESSION);
 		    // return json_decode($res, true);
 		    if (!empty($json_obj['access_token'])) {
 		        // 根据openid和access_token查询用户信息
 		        // dump($json_obj);
 		        return $json_obj;
 		    }else {
 		
 		        return -1001;
 		    }
 		}
 		
 		////////////////////////////////////微信授权结束 */
	
	
	
	//财务日志
	public function addFinance($sz_type,$type,$money,$content,$openid){
	    //sz_type 1 收入 2 支出
	    //$type  1余额 2 积分
	    if(!$openid){
	        $data['open_id'] = session('openid');
	    }else{
	        $data['open_id'] = $openid;
	    }
		
		if(!$data['open_id']){
		    $this->ajaxReturn(['status'=>-1,'msg'=>'系统繁忙，请稍后再试'],'JSONP');
		}
		$data['sz_type'] = $sz_type;
		$data['type']    = $type;
		$data['content'] = $content;
		$data['money'] = $money;
		$data['addtime'] = time();
		$r = M('Finance')->add($data);
		if($r){
			return true;
		}else{
			return false;
		}
	}
	//查财务日志
	public function selectFinance($type){
	    //$type  1余额 2 积分
	    $open_id = session('openid');
		$list = M('Finance')->where(array('type'=>$type,'open_id'=>$open_id))->order('addtime desc')->select();
		foreach($list as $k=>$v){
			if($v['sz_type'] == 1){
				$list[$k]['sz_type'] = "收入";
			}
			if($v['sz_type'] == 2){
				$list[$k]['sz_type'] = "支出";
			}
			if($v['type'] == 2){
			    $list[$k]['type'] = "积分";
			}
			if($v['type'] == 1){
			    $list[$k]['type'] = "余额";
			}
		}
		return $list;
	}
	/*   分享       */
	public function getSignPackage($url) {
		$jsapiTicket = $this->getJsApiTicket();
		// 注意 URL 一定要动态获取，不能 hardcode.
		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		// 		$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		$timestamp = time();
		$nonceStr = $this->createNonceStr();
	
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
	
		$signature = sha1($string);
		//分享内容
		$order_id=I('order_id');
		$open_id=I('open_id');
		if($open_id){
			///查询订单是否存在
			$order=M('rob_orders')->where(array('order_id'=>$order_id))->find();
			if($order){
				/* $url='http://'.$_SERVER['HTTP_HOST'].'Home/RobOrder/orderInvite/order_id/'.$order_id; */
				//查询发起邀请语
				$yao=M('yaoq')->where(array('rob_order'=>$order_id))->find();
				$detail=M('rob_goods_orders')->where(array('order_id'=>$order_id))->find();
				$content=$yao['content'];
				$img=$detail['image'];
				/* $this->ajaxReturn(['status' => 1,'url'=>$url,'content'=>$content,'img'=>$img, 'msg' => '获取成功']); */
			}else{
				$this->ajaxReturn(['status' => -3, 'msg' => '订单不存在']);
			}
		}else{
			$this->ajaxReturn(['status' => -2, 'msg' => '重新登陆没有openid']);
		}
		$signPackage = array(
				"appId"     => 'wx57b559484ac7a0c1',
				"nonceStr"  => $nonceStr,
				"timestamp" => $timestamp,//当前时间
				"url"       => $url,    //地址
				"signature" => $signature,
				"rawString" => $string,
				'img'       => $img,
				'content'   => $content,
		);
		return $signPackage;
	}
	public function fenxiang($url){
		$arr=$this->getSignPackage($url);
		$this->ajaxReturn($arr);
	}
	private function getJsApiTicket() {
		// jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
		$data = json_decode($this->get_php_file("jsapi_ticket.php"));
		if ($data->expire_time < time()) {
			$accessToken = $this->getWxAccessToken();
			// 如果是企业号用以下 URL 获取 ticket
			// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
			$res = json_decode( $this->http($url, 'GET')[1]);
			$ticket = $res->ticket;
			if ($ticket) {
				$data->expire_time = time() + 7000;
				$data->jsapi_ticket = $ticket;
				$this->set_php_file("jsapi_ticket.php", json_encode($data));
			}
		} else {
			$ticket = $data->jsapi_ticket;
		}
	
		return $ticket;
	}
	private function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}
	public function getWxAccessToken(){
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->AppID.'&secret='.$this->AppSecret;
		$access_token = $this->http($url, 'GET');
		$access_token = json_decode($access_token[1],true);
		//dump($access_token);
		return  $access_token['access_token'];
	}
	private function get_php_file($filename) {
		return trim(substr(file_get_contents($filename), 15));
	}
	private function http($url, $method, $postfields = null, $headers = array(), $debug = false) {
		$ci = curl_init ();
		/* Curl settings */
		curl_setopt ( $ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
		curl_setopt ( $ci, CURLOPT_CONNECTTIMEOUT, 30 );
		curl_setopt ( $ci, CURLOPT_SSL_VERIFYPEER, FALSE );
		curl_setopt ( $ci, CURLOPT_SSL_VERIFYHOST, FALSE );
		curl_setopt ( $ci, CURLOPT_TIMEOUT, 30 );
		curl_setopt ( $ci, CURLOPT_RETURNTRANSFER, true );
	
		switch ($method) {
			case 'POST' :
				curl_setopt ( $ci, CURLOPT_POST, true );
				if (! empty ( $postfields )) {
					curl_setopt ( $ci, CURLOPT_POSTFIELDS, $postfields );
					$this->postdata = $postfields;
				}
				break;
		}
		curl_setopt ( $ci, CURLOPT_URL, $url );
		curl_setopt ( $ci, CURLOPT_HTTPHEADER, $headers );
		curl_setopt ( $ci, CURLINFO_HEADER_OUT, true );
	
		$response = curl_exec ( $ci );
		$http_code = curl_getinfo ( $ci, CURLINFO_HTTP_CODE );
	
		if ($debug) {
			echo "=====post data======\r\n";
			var_dump ( $postfields );
	
			echo '=====info=====' . "\r\n";
			print_r ( curl_getinfo ( $ci ) );
	
			echo '=====$response=====' . "\r\n";
			print_r ( $response );
		}
		curl_close ( $ci );
		return array (
				$http_code,
				$response
		);
	}
	private function set_php_file($filename, $content) {
		$fp = fopen($filename, "w");
		fwrite($fp, "<?php exit();?>" . $content);
		fclose($fp);
	}
	
}